import jwt.exceptions
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
from user import models
from utils.jwttool import tool

class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token=request.META.get('HTTP_AUTHORIZATION','')
        if not token:
            raise AuthenticationFailed('请先登录,并设置token')
        try:
            rettoken=token.split(' ')[1]
            payload=tool.checkToken(rettoken)
            user=models.UserModel.objects.get(id=payload['userid'])
            return (user,payload)
        except jwt.ExpiredSignatureError as e:
            raise AuthenticationFailed(f'请先登录{e}')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('token过期')